package com.lxu.report.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.*;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *重构XWPFDocument中 不合格的 占位符 比如：${abcd}分开为${a，b..,cd}
 */
public class XWPFDocumentRefactorUtils {

    public static void refactorXWPFDocument(XWPFDocument doc) {
        try {
            buildParagraph(doc);
            buildTable(doc);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void buildParagraph(XWPFDocument document){
        for (XWPFParagraph paragraph : document.getParagraphs()) {
            if (matcher(paragraph.getText()).find()) {
                removeEmptyRun(paragraph);
                refactorParagraph(paragraph);
            }
        }
    }

    public static Matcher matcher(String str) {
        Pattern pattern = Pattern.compile("\\$\\{(.+?)\\}", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(str);
        return matcher;
    }

    private static void removeEmptyRun(XWPFParagraph paragraph) {
        List<XWPFRun> runsq = paragraph.getRuns();
        for (int i = 0; i <runsq.size() ; i++) {
            String runText = runsq.get(i).toString();
            if (StringUtils.isEmpty(runText)){
                paragraph.removeRun(i);
                break;
            }
        }
        for (int i = 0; i <runsq.size() ; i++) {
            String runText = runsq.get(i).toString();
            if (StringUtils.isEmpty(runText)){
                removeEmptyRun(paragraph);
                break;
            }
        }
    }

    public static void refactorParagraph(XWPFParagraph paragraph) {
        int start = -1;
        int end = -1;
        List<XWPFRun> runs = paragraph.getRuns();
        for (int i = 0; i < runs.size() ; i++) {
            String runText = runs.get(i).toString();
            if ('$' == runText.charAt(0)&&'}' == runText.charAt(runText.length() - 1)){
                continue;
            }
            if ('$' == runText.charAt(0)){
                start = i;
            }
            if ('}' == runText.charAt(runText.length() - 1)){
                end = i;
                break;
            }
        }
        if (start != -1){
            mergeRun(paragraph,start,end);
            refactorParagraph(paragraph);
        }
    }

    public static void mergeRun(XWPFParagraph paragraph, int start, int end) {
        int removeCount = end-start;//删除次数
        int removeIndex = start+1;//删除开始位置

        List<XWPFRun> runs = paragraph.getRuns();
        for (int i = 0; i <runs.size() ; i++) {
            System.out.println(runs.get(i).toString());
        }
        StringBuilder sb = new StringBuilder();
        sb.append(runs.get(start).toString());

        for (int i = 0; i < removeCount; i++){
            sb.append(runs.get(removeIndex).toString());
            paragraph.removeRun(removeIndex);
        }
        runs.get(start).setText(sb.toString(),0);
    }

    public static void buildTable(XWPFDocument document){
        List<XWPFTable> tables = document.getTables();
        for (XWPFTable xwpfTable : tables) {
            List<XWPFTableRow> rows = xwpfTable.getRows();
            for (XWPFTableRow row :rows){
                List<XWPFTableCell> tableCells = row.getTableCells();
                for (XWPFTableCell tableCell : tableCells){
                    List<XWPFParagraph> paragraphs = tableCell.getParagraphs();
                    for (XWPFParagraph paragraph : paragraphs){
                        if (matcher(paragraph.getText()).find()) {
                            removeEmptyRun(paragraph);
                            refactorParagraph(paragraph);
                        }
                    }
                }
            }

        }
    }
}
